/*The MIT License

Copyright (c) <2008> <Samir Menon>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#include "CDCaKNaNeuron.h"

namespace bis_neuron
{
	using namespace std;

CDCaKNaNeuron::CDCaKNaNeuron(const int &  arg_num_da_synapses, 
														 const int &  arg_num_stdp_synapses) 
														 : CSynCaKNaNeuron(arg_num_stdp_synapses)
	{
		//Synapse
		delta_i_ca = 0.15;
		g_k_kir2 = 0.0;
		assert(arg_num_da_synapses>=0);
		num_da_synapses = arg_num_da_synapses;
		da_synapse = new CSynapse[arg_num_da_synapses];
	}
	
	CDCaKNaNeuron::CDCaKNaNeuron(const float & arg_tau_ca, const float & arg_i_ca_max, 
									const unsigned int & arg_num_da_synapses,  
								 const unsigned int & arg_stdp_synapses, 
								 const float & arg_delta_i_ca, const float & arg_r_ca,
								 const float & arg_tau_k, const float & arg_delta_gk,
								 const float & arg_sigma, const float & arg_n) 
											 :	CSynCaKNaNeuron(arg_tau_ca, arg_i_ca_max, arg_stdp_synapses, 
													 arg_delta_i_ca, arg_r_ca, arg_tau_k, arg_delta_gk, arg_sigma, arg_n) 
	{
		assert(arg_num_da_synapses>=0);
		g_k_kir2 = 0.0;
		num_da_synapses = arg_num_da_synapses;
		da_synapse = new CSynapse[arg_num_da_synapses];
		//TODO: Add specific dopamine synapse code
	}
	
	void CDCaKNaNeuron::reset_neuron()
	{	
		unsigned int i;
		vm = 0.0; v_na = 0.0;	g_k = 0.0; g_k_hold = 0.0;//Na-K part
		i_ca = 0.0; i_ca_hold = 0.0;//Ca part
		for(i=0;i<num_stdp_synapses;i++)//Stdp Synapses
		{
			stdp_synapse[i].reset();
		}		
		g_k_hold = 0.0;	g_k_kir2 = 0.0; //Kir2 part
		for(i=0;i<num_da_synapses;i++)
		{
			da_synapse[i].reset();
		}
	}
			
	void CDCaKNaNeuron::set_data(const float & arg_r, const float & arg_sigma, 
											 const float & arg_n, const float & arg_tau_k,
											 const float & arg_delta_gk,
											 const float & arg_tau_ca, const float & arg_r_ca, 
											 const float & arg_delta_i_ca)
	{	
		r = arg_r; sigma = arg_sigma; n = arg_n;
		tau_k = arg_tau_k; delta_gk = arg_delta_gk;
		tau_ca = arg_tau_ca; r_ca = arg_r_ca; delta_i_ca = arg_delta_i_ca;
	}
	
	CDCaKNaNeuron::~CDCaKNaNeuron()
	{
		if(NULL!=da_synapse){
			delete [] da_synapse;
		}
	}

	
	void CDCaKNaNeuron::activate_da_synapse(const unsigned int & arg_da_syn_id)
	{
		NEURON_CLOCK time_this_instant = clock->get_time();
		assert(arg_da_syn_id < num_da_synapses);		
		vm = vm + da_synapse[arg_da_syn_id].syn_vm_jump();
		da_synapse[arg_da_syn_id].pre_event(time_this_instant);
	}
	
	void CDCaKNaNeuron::set_da_synapse(const unsigned int & arg_neuron_from,
													const unsigned int & arg_to_synapse,
													const float & arg_non_pot_syn_strength,
													const float & arg_pot_syn_strength)
	{
		assert(arg_to_synapse < num_da_synapses);
		da_synapse[arg_to_synapse].set_from_neuron(arg_neuron_from);
		da_synapse[arg_to_synapse].set_syn_strength(arg_non_pot_syn_strength,
																								arg_pot_syn_strength);
	}
	
	inline float CDCaKNaNeuron::return_gk_kir2()
	{
		//Here we model the kir2 inward rectifying channel using a cubic y = (a-x)*(b-x)*(c-x)
		//vm < a 						: Down state - Stable Eq
		//vm == a 					: Unstable Eq state for neuron between down and up states
		//a < vm < b				: Up state - Stable Eq, neuron pushed towards b
		//a < vm < (b+c)/2	: Up state - Stable Eq, neuron gets pulled back towards b
		//vm > (b+c)/2			: Neuron will tend to fire normally though bistability currents exist
		//vm > c						: Effects of bistability fade and neuron fires - Should be at critical point for action potential.
		if(vm < KIR2_A)	{	return KIR2_DOWN;	}
		else if((vm >= KIR2_A)&&(vm < KIR2_B))	{	return -1*KIR2_MED;	}
		else if((vm >= KIR2_B)&&(vm < KIR2_C))	{	return KIR2_UP;	}
		else {	return 0.0;	}
		
		//vm == a 					: Unstable Eq state for neuron between down and up states
		//a < vm < b				: Up state - Stable Eq, neuron pushed towards b
		//a < vm < (b+c)/2	: Up state - Stable Eq, neuron gets pulled back towards b
		//vm > (b+c)/2			: Neuron will tend to fire normally though bistability currents exist
		//vm > c						: Effects of bistability fade and neuron fires - Should be at critical point for action potential.
		
//		return (KIR2_A - vm)*(KIR2_B - vm)*(KIR2_C - vm);
	}

	bool CDCaKNaNeuron::fire()
	{//Progress one time-cycle
		if(execution_flag < 1) {return false;}
		if(clock == NULL) {	execution_flag = -1; return false;}
		return update_vm();		
	}
	
	inline bool CDCaKNaNeuron::update_vm()
	{
		//Sodium channel excitability dependent n and sigma
		//TODO: Replace rand() with randn() where
		//randn() gives a normally distributed var [0,1]
		
		assert(tau_k != 0);
		assert(tau_ca != 0);
		
		v_na=0.0+exp(sigma*(rand()/RAND_MAX)*n); 
		float g=0.0, temp;
		float vm_delta = 0.0;
		unsigned int i=0;
		
		if (vm >= vm_max){//Spike	
			vm = 0;
			log_data();
			log_spike();
			temp = clock->get_time();
			temp = -(temp - t_last_spike);
			g_k = (g_k* exp(temp/tau_k) + delta_gk);
			i_ca = i_ca_hold + delta_i_ca;
	//		i_ca = i_ca_hold + 0.25 * (i_ca_max - i_ca);
			t_last_spike = clock->get_time();
			
			for(i=0;i<num_stdp_synapses;i++){	stdp_synapse[i].post_event(t_last_spike);	}
			for(i=0;i<num_da_synapses;i++){	da_synapse[i].post_event(t_last_spike);	}
			
			return true;//Spike
		}
		else if (vm < vm_min){ //Membrane potential underflow
			vm = vm_min;
		}
		else{//Increment membrane potential -> Cubic growth
			temp = clock->get_time();
			temp = -(temp - t_last_spike);
			if(vm < VM_BISTABLE){	g_k_kir2 = return_gk_kir2();	}
			g_k_hold = g_k * exp(temp/tau_k);
			g = g + g_k_hold + g_k_kir2;
			i_ca_hold = i_ca * exp(temp/tau_ca);//Exponential Ca decay
			
			vm_delta =(-vm*(1+g) + r + v_na * pow(vm,3)/3);
			vm_delta = SCALING_FACTOR * vm_delta;
			vm = vm + vm_delta + (i_ca_hold*r_ca);
			if (vm >= vm_max){//Spike
				vm = vm_max;
			}
			log_data();
		} 
		return false;//No spike
	}
	
	void CDCaKNaNeuron::log_data(){
		string log_dump;
		if(data_spooler == NULL) { return;	}		
		if(true == log_data_flag){
			data_log_stream<<vm<<"   "<<g_k_hold<<"	"<<g_k_kir2<<"	"<<t_last_spike;
			log_dump.clear();
			log_dump += data_log_stream.str();
			data_spooler->spool_data(neuron_id,&log_dump);
			data_log_stream.str("");
		}		
	}
}
